//
//  TTRecyclingValuationViewController.m
//  TaoTuo
//
//  Created by LG on 2020/8/8.
//  Copyright © 2020 刘广. All rights reserved.
//

#import "TTRecyclingValuationViewController.h"
//#import "LLSegmentView.h"
#import "TTDianpuUploadImageModel.h"
#import "TTDianpuUploadImageCollectionViewCell.h"
#import "LLImagePicker.h"
#import "YBImageBrowser.h"
#import "OSSRecyclingImageUploader.h"
#import "TTSendButtonView.h"
#import "TTEstimateDetailViewController.h"
#import "TTRecyclingSendViewController.h"

static NSString *cellID = @"upload_cell_id";

static NSString *addImageName = @"addimage";

@interface TTRecyclingValuationViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, TTDianpuUploadImageCollectionViewCellDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIScrollViewDelegate>
{
    TTDianpuUploadImageModel *lastModel;
}

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSMutableArray *imgUrlArray;  //上传的图片地址
///图片最大上传数量
@property (nonatomic, assign) int imageUploadMaxCount;

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UILabel *uploadLabel;
@property (nonatomic, strong) UILabel *infoLabel;
@property (nonatomic, strong) YYTextView *textView;

@property (nonatomic, strong) TTSendButtonView *bottomView;
@property (nonatomic, strong) UIButton *commitBtn;

@end

@implementation TTRecyclingValuationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = self.Reclaim_InformationId ? @"完善信息" : @"回收估价";
    [self setupSubviews];
    [self setupDatas];
    
    
    [self addObserver:self forKeyPath:@"dataArray" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"dataArray"]) {
        [self.bottomView setButtonEnabled:self.dataArray.count > 1];
        self.commitBtn.enabled = self.dataArray.count > 1;
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    TTDianpuUploadImageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    [cell setModel:self.dataArray[indexPath.row] canModify:YES];
    cell.delegate = self;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    TTDianpuUploadImageModel *model = self.dataArray[indexPath.row];
    if ([model.imageName isEqualToString:addImageName]) {
        [LLImagePicker imagePickerWithMaxImagesCount:(7 - self.dataArray.count) delegate:self baseViewController:self didFinishPickingPhotosHandle:^(NSArray<UIImage *> * _Nonnull photos, BOOL isSelectOriginalPhoto) {
            //上传图片到OSS, 添加model
            [[OSSRecyclingImageUploader sharedLoader] asyncUploadImages:photos complete:^(NSArray<NSString *> * _Nonnull names, UploadImageState state) {
                NSLog(@">>>> %@, state = %ld", names, state);
                for (NSString *urlStr in names) {
                    TTDianpuUploadImageModel *imgModel = [[TTDianpuUploadImageModel alloc] init];
                    imgModel.imageUrlString = urlStr;
                    [[self mutableArrayValueForKey:@"dataArray"] insertObject:imgModel atIndex:self.dataArray.count - 1];
                    [self.imgUrlArray insertObject:urlStr atIndex:self.imgUrlArray.count];
                }
                
                if (self.dataArray.count >= 7) {
                    [[self mutableArrayValueForKey:@"dataArray"] removeLastObject];
                }
                
                [self setupCollectionViewHeight];
                
                [self.collectionView reloadData];
            }];
        }];
        
    } else {
        // 查看图片
        @autoreleasepool {
            NSMutableArray *imgs = [NSMutableArray array];
            for (TTDianpuUploadImageModel *model in self.dataArray) {
                if (model.imageUrlString.length > 0) {
                    YBIBImageData *imageData = [YBIBImageData new];
                    imageData.imageURL = [NSURL URLWithString:model.imageUrlString];
                    [imgs addObject:imageData];
                }
            }
            YBImageBrowser *browser = [YBImageBrowser new];
            browser.dataSourceArray = imgs;
            browser.currentPage = indexPath.row;
            [browser show];
        }
        
    }
}


- (void)setupCollectionViewHeight
{
    CGFloat h = floor((self.view.width - 40) / 3.0);
    CGFloat rowCount = ceilf(self.dataArray.count / 3.0);
    [self.collectionView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(rowCount * h + 10);
    }];
    [self.textView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.collectionView.mas_bottom).mas_offset(23);
    }];
    
    [self.view layoutIfNeeded];
    
    CGFloat contentSizeH = self.textView.bottom + 30;
    contentSizeH = contentSizeH > self.view.height ? contentSizeH : self.view.height;
    self.scrollView.contentSize = CGSizeMake(kScreenWidth, contentSizeH);
    
}

// 拍照或选取图片完成
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info
{
    // 图片
    UIImage *image = info[UIImagePickerControllerEditedImage];
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    //上传图片到OSS, 添加model
    [[OSSRecyclingImageUploader sharedLoader] asyncUploadImage:image complete:^(NSArray<NSString *> * _Nonnull names, UploadImageState state) {
        NSLog(@">>>> %@, state = %ld", names, state);
        NSString *urlStr = names.firstObject;
        TTDianpuUploadImageModel *imgModel = [[TTDianpuUploadImageModel alloc] init];
        imgModel.imageUrlString = urlStr;
        [[self mutableArrayValueForKey:@"dataArray"] insertObject:imgModel atIndex:0];
        [self.imgUrlArray insertObject:urlStr atIndex:0];
        [self.collectionView insertItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]]];
        if (self.dataArray.count >= 7) {
            [[self mutableArrayValueForKey:@"dataArray"] removeLastObject];
            [self.collectionView reloadData];
        }
        
        [self setupCollectionViewHeight];
        
    }];
    
}

#pragma mark - TTDianpuUploadImageCollectionViewCellDelegate
// 删除图片
- (void)imageCell:(TTDianpuUploadImageCollectionViewCell *)imageCell deleteModel:(TTDianpuUploadImageModel *)model
{
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:imageCell];
    [[self mutableArrayValueForKey:@"dataArray"] removeObject:model];
    [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
    
    if (self.dataArray.lastObject != lastModel) {
        [[self mutableArrayValueForKey:@"dataArray"] addObject:lastModel];
    }
    [self.collectionView reloadData];
    [self setupCollectionViewHeight];
    
    for (NSString *urlStr in self.imgUrlArray) {
        if ([urlStr isEqualToString:model.imageUrlString]) {
            [self.imgUrlArray removeObject:urlStr];
            break;
        }
    }
}


- (void)setupDatas
{
    [[self mutableArrayValueForKey:@"dataArray"] removeAllObjects];
    // 添加一个添加图片的按钮
    lastModel = [[TTDianpuUploadImageModel alloc] init];
    lastModel.imageName = addImageName;
    [[self mutableArrayValueForKey:@"dataArray"] addObject:lastModel];
    
    [self.collectionView reloadData];
    
}


- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.y < 0) {
        [self.view endEditing:YES];
    }
}

/// 完善信息再次提交数据
- (void)commitDatas
{
    NSDictionary *dic = @{
        @"RealName" : [TTLoginSingle sharedSingle].loginModel.RealName,
        @"Reclaim_InformationId" : self.Reclaim_InformationId,
        @"Uri" : self.imgUrlArray,
        @"Remark" : self.textView.text
    };
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] postJsonWithUrlString:recyclingPerfectInfo_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        [self.navigationController popViewControllerAnimated:YES];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"deleteGoods_notify_key" object:nil];
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.view];
}

- (void)setupSubviews
{
    _scrollView = [[UIScrollView alloc] init];
    _scrollView.contentSize = CGSizeMake(kScreenWidth, self.view.height);
    _scrollView.delegate = self;
    [self.view addSubview:_scrollView];
    [_scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mas_topLayoutGuideBottom);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view).mas_offset(-66);
    }];
    
    NSString *str = self.Reclaim_InformationId ? @"请进一步上传实物/证书图片" : @"请上传实物/证书图片";
    _uploadLabel = [UILabel labelWithTitle:str color:UIColorHex(#333333) font:[UIFont fontWithName:@"DINAlternate-Bold" size:15]];
    [self.scrollView addSubview:_uploadLabel];
    [_uploadLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(9);
        make.left.mas_equalTo(15);
    }];
    NSString *info = self.reasonStr ? self.reasonStr : @"真实的图片有利于我们的鉴定和估价";
    _infoLabel = [UILabel labelWithTitle:info color:UIColorHex(#999999) fontSize:13];
    [self.scrollView addSubview:_infoLabel];
    [_infoLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.uploadLabel.mas_bottom).mas_offset(5.5);
        make.left.equalTo(self.uploadLabel);
    }];
    
    CGFloat h = floor((self.view.width - 40) / 3.0) + 5;
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.infoLabel.mas_bottom).mas_offset(15);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(h);
    }];
    
    _textView = [[YYTextView alloc] init];
    _textView.backgroundColor = UIColorHex(#F7F7F7);
    _textView.placeholderText = @"请备注货品详细信息，有利于我们更好估价";
    _textView.placeholderFont = [UIFont systemFontOfSize:13];
    _textView.font = [UIFont systemFontOfSize:13];
    _textView.textColor = UIColorHex(#333333);
    [self.scrollView addSubview:_textView];
    [_textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.collectionView.mas_bottom).mas_offset(23);
        make.left.equalTo(self.uploadLabel);
        make.right.equalTo(self.view).mas_offset(-15);
        make.height.mas_equalTo(120*kScale);
    }];
    
    if (self.Reclaim_InformationId) {
        
        UIButton *commitBtn = [UIButton createButtonWithTitle:@"提交" titleColor:[UIColor whiteColor] titleFont:[UIFont boldSystemFontOfSize:17] backgroundColor:nil cornerRadius:20 target:self action:@selector(commitDatas)];
        commitBtn.layer.masksToBounds = YES;
        [commitBtn setTitleColor:UIColorHex(#999999) forState:UIControlStateDisabled];
        [commitBtn setBackgroundImage:[UIImage imageWithColor:UIColorHex(#DEDEDE)] forState:UIControlStateDisabled];
        [commitBtn setBackgroundImage:[UIImage imageWithColor:UIColorHex(#9343EB)] forState:UIControlStateNormal];
        [self.view addSubview:commitBtn];
        commitBtn.enabled = NO;
        self.commitBtn = commitBtn;
        [commitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.view).mas_offset(-24);
            make.height.equalTo(@40);
            make.left.equalTo(@15);
            make.right.equalTo(@-15);
        }];
        
    } else {
        
        @weakify(self)
        _bottomView = [TTSendButtonView createSendButtonViewAndClickSendButtonBlock:^{
            @strongify(self)
            [self sendBtnClick];
        } startValuationBtnBlock:^{
            @strongify(self)
            [self startValuationBtnClick];
        }];
        [self.view addSubview:_bottomView];
        [_bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.view).mas_offset(-24);
            make.height.equalTo(@40);
            make.left.equalTo(@15);
            make.right.equalTo(@-15);
        }];
    }
    

}

/// 直接寄送
- (void)sendBtnClick
{
    [self commitZSInfoSuccess:^(NSString *infoID) {
        TTRecyclingSendViewController *sendVC = [[TTRecyclingSendViewController alloc] init];
        sendVC.Reclaim_InformationId = infoID;
        [[LLRouteTool getCurrentNavigationController] pushViewController:sendVC animated:YES];
    }];
}

/// 开始估价
- (void)startValuationBtnClick
{
    [self commitZSInfoSuccess:^(NSString *infoID) {
       TTEstimateDetailViewController *detailVC = [[TTEstimateDetailViewController alloc] init];
        detailVC.Reclaim_InformationId = infoID;
        [[LLRouteTool getCurrentNavigationController] pushViewController:detailVC animated:YES];
    }];
    
}

- (void)commitZSInfoSuccess:(void(^)(NSString *infoID))success
{
    NSMutableDictionary *dic = @{
        @"RealName" : [TTLoginSingle sharedSingle].loginModel.RealName,
        @"SalesmanAccountName" : [TTLoginSingle sharedSingle].loginModel.SalesmanAccountName,
        @"Uri" : self.imgUrlArray,
        @"Remark" : self.textView.text,
        @"SalesmanMobile" : [TTLoginSingle sharedSingle].loginModel.SalesmanMobile
    }.mutableCopy;
    if (self.Reclaim_InformationId) {
        [dic setObject:self.Reclaim_InformationId forKey:@"Reclaim_InformationId"];
    }
    
    [[LLNetworkManagerTool sharedManager] postJsonWithUrlString:submitInformation_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        success(responseObject[@"Reclaim_InformationId"]);
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.view];
}


- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        CGFloat w = floor((self.view.width - 40) / 3.0);
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = CGSizeMake(w, w);
        layout.minimumLineSpacing = 5;
        layout.minimumInteritemSpacing = 0;
        layout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = [UIColor whiteColor];
        [_collectionView registerClass:[TTDianpuUploadImageCollectionViewCell class] forCellWithReuseIdentifier:cellID];
        [self.scrollView addSubview:_collectionView];
    }
    return _collectionView;
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (NSMutableArray *)imgUrlArray
{
    if (!_imgUrlArray) {
        _imgUrlArray = [NSMutableArray array];
    }
    return _imgUrlArray;
}

- (void)dealloc
{
    [self removeObserver:self forKeyPath:@"dataArray"];
}

@end
